package cn.ming.wfchat.app.main;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.ButterKnife;
import cn.ming.wfchat.R;
import cn.ming.wfchat.app.AppService;
import cn.ming.wfchat.app.dialog.PaymentDialog;
import cn.ming.wfchat.app.dynamic.adpter.NetWorkListAdapter;
import cn.ming.wfchat.app.dynamic.bean.NetWorkCountBean;
import cn.ming.wfchat.app.dynamic.bean.ValidateNetWorkBean;
import cn.ming.wfchat.app.me.activity.BuddyListActivity;
import cn.ming.wfchat.app.me.activity.FindNetWorkActivity;
import cn.ming.wfchat.kit.contact.ContactViewModel;
import cn.ming.wfchat.kit.contact.model.UIUserInfo;
import cn.ming.wfchat.kit.net.base.StatusResult;
import cn.ming.wfchat.kit.utils.Tools;
import cn.wildfirechat.remote.ChatManager;

/**
 * 关系网
 */
public class NetWorkFragment extends Fragment implements View.OnClickListener {


    private RecyclerView recyclerView;
    protected NetWorkListAdapter userListAdapter;
    protected ContactViewModel contactViewModel;
    private TextView tv_text;
    private TextView tv_yi_number;
    private TextView tv_er_number;
    private TextView tv_san_number;
    private TextView tv_si_number;
    private TextView tv_wu_number;
    private LinearLayout ll_layout;
    private TextView tv_jiaru;

    private String relationAmount;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_fragment_network, container, false);
        recyclerView = view.findViewById(R.id.recycler_view);
        tv_text = view.findViewById(R.id.tv_text);
        tv_yi_number = view.findViewById(R.id.tv_yi_number);
        tv_er_number = view.findViewById(R.id.tv_er_number);
        tv_san_number = view.findViewById(R.id.tv_san_number);
        tv_si_number = view.findViewById(R.id.tv_si_number);
        tv_wu_number = view.findViewById(R.id.tv_wu_number);
        tv_jiaru = view.findViewById(R.id.tv_jiaru);

        ll_layout = view.findViewById(R.id.ll_layout);
        view.findViewById(R.id.ll_yi).setOnClickListener(this);
        view.findViewById(R.id.ll_er).setOnClickListener(this);
        view.findViewById(R.id.ll_san).setOnClickListener(this);
        view.findViewById(R.id.ll_si).setOnClickListener(this);
        view.findViewById(R.id.ll_wu).setOnClickListener(this);
        ButterKnife.bind(this, view);
        return view;
    }


    private void init() {
        contactViewModel = ViewModelProviders.of(getActivity()).get(ContactViewModel.class);
        userListAdapter = new NetWorkListAdapter();
        userListAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if (view.getId() == R.id.tv_join) {
                    PaymentDialog.newInstance("付款", relationAmount + "USDT").setOnClickListener(new PaymentDialog.OnClickListener() {
                        @Override
                        public void getPwd(String pwd) {
                            Joinetwork(pwd, userListAdapter.getData().get(position).getUserInfo().uid);
                        }
                    }).show(getActivity());
                }
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        congfigFind();
        AppService.Instance().validateNetWork(new AppService.FindNetWorkCallback() {
            @Override
            public void onUiSuccess(ValidateNetWorkBean assetsBean) {
                if (assetsBean.isWhetherNetWork()) {
                    tv_text.setVisibility(View.GONE);
                    tv_jiaru.setVisibility(View.GONE);
                    findNetWorkCount();
                } else {
                    if (assetsBean.isWhetherIntoNetWork()) {
                        tv_text.setVisibility(View.VISIBLE);
                        tv_jiaru.setVisibility(View.VISIBLE);
                        findNetWorkCount();
                    } else {
                        showFriendsList();
                    }
                }

            }

            @Override
            public void onUiFailure(int code, String msg) {
                ChatManager.showToast(msg);

            }
        });
        tv_jiaru.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Tools.jump(getActivity(), FindNetWorkActivity.class, false);
            }
        });


    }

    /**
     * 获取配置信息
     */
    void congfigFind() {
        AppService.Instance().configFind("RELATION_AMOUNT", new AppService.ConfigFindCallback() {
            @Override
            public void onUiSuccess(ConfigFindBean assetsBean) {
                relationAmount = assetsBean.getValue();
                tv_text.setText("选择一位好友加入其关系网，需交付" + relationAmount + "USDT，且加入后不可退出。");
            }

            @Override
            public void onUiFailure(int code, String msg) {

            }
        });
    }

    /**
     * 显示好友列表
     */
    void showFriendsList() {
        recyclerView.setVisibility(View.VISIBLE);
        ll_layout.setVisibility(View.GONE);
        contactViewModel.contactListLiveData().observe(this, userInfos -> {
            List<UIUserInfo> uiUserInfoList = new ArrayList<>();
            if (userInfos != null) {
                for (UIUserInfo info : userInfos) {
                    if (Tools.isInteger(info.getUserInfo().uid)) {
                        uiUserInfoList.add(info);
                    }
                }
                userListAdapter.setNewData(uiUserInfoList);
                recyclerView.setAdapter(userListAdapter);
            }
        });
    }

    /**
     * 加入关系网
     */
    void Joinetwork(String pwd, String uid) {
        AppService.Instance().addNetWork(pwd, uid, new AppService.DynamicsLikesCallback() {
            @Override
            public void onUiSuccess(StatusResult assetsBean) {
                init();
            }

            @Override
            public void onUiFailure(int code, String msg) {
                ChatManager.showToast(msg);
            }
        });
    }

    /**
     * 显示5级好友数量
     */
    void findNetWorkCount() {
        recyclerView.setVisibility(View.GONE);
        ll_layout.setVisibility(View.VISIBLE);
        AppService.Instance().findNetWorkCount(new AppService.FindNetWorkCountCallback() {
            @Override
            public void onUiSuccess(NetWorkCountBean assetsBean) {
                tv_yi_number.setText(assetsBean.getCountOne() + "");
                tv_er_number.setText(assetsBean.getCountTwo() + "");
                tv_san_number.setText(assetsBean.getCountThree() + "");
                tv_si_number.setText(assetsBean.getCountFour() + "");
                tv_wu_number.setText(assetsBean.getCountFive() + "");
            }

            @Override
            public void onUiFailure(int code, String msg) {

            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (userListAdapter != null && isVisibleToUser) {
            init();
            contactViewModel.reloadContact();
            contactViewModel.reloadFriendRequestStatus();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        init();
        contactViewModel.reloadContact();
        contactViewModel.reloadFriendRequestStatus();
    }


    @Override
    public void onClick(View view) {
        Intent intent = new Intent(getContext(), BuddyListActivity.class);
        switch (view.getId()) {
            case R.id.ll_yi:
                intent.putExtra("level", "1");
                break;
            case R.id.ll_er:
                intent.putExtra("level", "2");
                break;
            case R.id.ll_san:
                intent.putExtra("level", "3");
                break;
            case R.id.ll_si:
                intent.putExtra("level", "4");
                break;
            case R.id.ll_wu:
                intent.putExtra("level", "5");
                break;
        }
        startActivity(intent);
    }
}
